package com.jf.assistant;

import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.GestureDescription;
import android.annotation.SuppressLint;
import android.app.KeyguardManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Path;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.PowerManager;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.Toast;

import androidx.annotation.RequiresApi;

import com.jf.bean.Action;
import com.jf.bean.AssistantTask;
import com.jf.controller.MainController;
import com.jf.utils.Sputils;
import com.test.Accessibility.utils.AccessUtils;
import com.xys.accessibilitydemo.utils.BaseAccessibilityService;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class MyAccessibilityService extends BaseAccessibilityService {
    String TAG="jiafan";

    public boolean isopenjingdong=false;

    public boolean isstarttag=false;

    public boolean isdingshi=false;

    public static MyAccessibilityService mMyAccessibilityService;

    String jingdongpackagename="com.jingdong.app.mall";
    public MyAccessibilityService() {

    }

    @Override
    protected void onServiceConnected() {
        super.onServiceConnected();
        isstarttag=false;
        mMyAccessibilityService=this;
        //Toast.makeText(getApplicationContext(),"wo connect",Toast.LENGTH_LONG).show();
        JfLog.logger("onServiceConnected");
    }

    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        JfLog.logger( "onAccessibilityEvent: "+event.getEventType());


        if (!isdingshi){

            isdingshi=true;
           // startThread();
           // startThread3();

            }



       // }

    }
    //AccessUtils
    public void findText(){
        AccessUtils.findText(getRootInActiveWindow(),mMyAccessibilityService,"呗壳",0);
    }
    public void findText2(){
        AccessUtils.findText(getRootInActiveWindow(),mMyAccessibilityService,"账单",0);
    }

    public  void   startThread3(){
        mthread= new Thread(new Runnable() {
            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void run() {

                while (true) {
                    //isdingshi=false;
                    try {
                        //Thread.sleep(3000);

                        Thread.sleep(10000);
                        time = time + 1;


                        JfLog.logger("借呗");
                        // AccessUtils.findText(this,"借呗");
                        AccessUtils.findText(getRootInActiveWindow(),mMyAccessibilityService,"呗",0);

                        //                             }
                        // Log.d(TAG, "onAccessibilityEvent: 在循环中" + time+" 集合中的数据："+assistantTasks.size());

                    } catch (InterruptedException e) {
                        JfLog.logger("异常：" + e.toString() );
                        e.printStackTrace();
                    }
                }

            }
        });

        mthread.start();

    }

    public   Thread mthread;
    public  void   startThread(){


        mthread= new Thread(new Runnable() {
            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void run() {

                while (true) {
                    //isdingshi=false;
                    try {
                        //Thread.sleep(3000);

                        Thread.sleep(40000);
                        time = time + 1;

                       // if (time % 4 == 0) {
                         //   wakeAndUnlock();

                       //     goApp(jingdongpackagename);
                      // mMyAccessibilityService.goApp(jingdongpackagename);

                        ArrayList<AssistantTask> assistantTasks = Sputils.getObject(MainController.ASSISTANT_TASKS, getApplicationContext());

                           // AccessUtils.ClickViewrootBytext(getRootInActiveWindow(),mMyAccessibilityService,"领京豆");
                            //Thread.sleep(3000);
                           // AccessUtils.ClickViewrootBytext(getRootInActiveWindow(),mMyAccessibilityService,"签到领京豆");
                        Date nowdate = new Date();
                        int nowhours = nowdate.getHours();
                        int nowminutes = nowdate.getMinutes();
                        JfLog.logger( " 当前时间："+nowhours+" : "+nowminutes );
                        for (AssistantTask assistantTask : assistantTasks){
                            Calendar starttime = assistantTask.getStarttime();
                            int taskhour= starttime.getTime().getHours();
                            int taskminutes= starttime.getTime().getMinutes();

                            JfLog.logger("当前任务名称：" + assistantTask.getTaskname()+" 当前时间："+nowhours+" : "+nowminutes );
                            if (nowhours==taskhour){
                                if (nowminutes==taskminutes){
                                    JfLog.logger("当前任务名称：" + assistantTask.getTaskname()+" 当前时间："+nowhours+" : "+nowminutes );
                                    ArrayList<Action> actions = assistantTask.getActions();
                                    wakeAndUnlock();

                                    Thread.sleep(2000);
                                    for (Action action :actions){
                                        wakeAndUnlock();
                                        startAction(action);
                                   }

//                                    AccessUtils.clickBackKey();
//                                    AccessUtils.clickBackKey();
//                                    AccessUtils.clickBackKey();
//                                    AccessUtils.clickBackKey();
//                                   clickHomeKey(mMyAccessibilityService);

                                }
                            }

                        }

                       //                             }
                       // Log.d(TAG, "onAccessibilityEvent: 在循环中" + time+" 集合中的数据："+assistantTasks.size());

                    } catch (InterruptedException e) {
                        JfLog.logger("异常：" + e.toString() );
                        e.printStackTrace();
                    }
                }

            }
        });

        mthread.start();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        JfLog.logger("mMyAccessibilityService  stop");
        stopThread();
        isdingshi=false;
    }

    public  void   stopThread(){
        if (mthread!=null){
            JfLog.logger("onDestroy： 关闭线程" );
            mthread.stop();
        }
    }




    public  void   startThread1(){

       // goApp(jingdongpackagename);
        new Thread(new Runnable() {
            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void run() {

                while (true) {
                    //isdingshi=false;
                    try {
                        Thread.sleep(3000);

                        //Thread.sleep(60000);
                        time = time + 1;

                         if (time % 4 == 0) {
                             wakeAndUnlock();

                            // goApp(jingdongpackagename);

                             Thread.sleep(5000);
                             AccessUtils.ClickViewrootBytext(getRootInActiveWindow(),mMyAccessibilityService,"1");
                             Thread.sleep(3000);
                             AccessUtils.ClickViewrootBytext(getRootInActiveWindow(),mMyAccessibilityService,"1");
                             Thread.sleep(3000);
                             AccessUtils.ClickViewrootBytext(getRootInActiveWindow(),mMyAccessibilityService,"1");

                             Thread.sleep(3000);
                             AccessUtils.ClickViewrootBytext(getRootInActiveWindow(),mMyAccessibilityService,"1");

                             Thread.sleep(3000);
                             AccessUtils.ClickViewrootBytext(getRootInActiveWindow(),mMyAccessibilityService,"1");

                             Thread.sleep(3000);
                             AccessUtils.ClickViewrootBytext(getRootInActiveWindow(),mMyAccessibilityService,"1");


                             //  mMyAccessibilityService.goApp(jingdongpackagename);
                       //  AccessUtils.ClickViewrootBytext(getRootInActiveWindow(),mMyAccessibilityService,"领京豆");
                           // Thread.sleep(3000);
                         //AccessUtils.ClickViewrootBytext(getRootInActiveWindow(),mMyAccessibilityService,"签到领京豆");
                             JfLog.logger("onAccessibilityEvent: 在循环中" + time);


                    }


                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

            }
        }).start();
    }
    // 按home
    public static void clickHomeKey(AccessibilityService mAccessibilityService) throws InterruptedException {



        mAccessibilityService.performGlobalAction(AccessibilityService.GLOBAL_ACTION_HOME);
        Thread.sleep(1000);



    }

    public void startAction(Action maction) throws InterruptedException {
        Log.e("服务中进行的操作：",maction.getType()+":"+maction.getActionname());
        switch (maction.getType()){
            case Action.ACTIONNAME:
                JfLog.logger("开始自动化的任务是："+maction.getActionname());

                break;
            case Action.START_TIME:
                JfLog.logger("开始自动化的任务时间分："+maction.getStarttime().getTime().getMinutes());
                break;
            case Action.OPENAPP:

                JfLog.logger("打开app："+maction.getOpenappname());
                JfLog.logger("打开app包名:"+maction.getOpenapppackage().toString().trim());
                //mMyAccessibilityService.goApp("com.jingdong.app.mall");
                goApp("com.jf.assistant");
                Thread.sleep(2000);
                mMyAccessibilityService.goApp(maction.getOpenapppackage().toString().trim());
                break;
            case Action.DELAY:
                JfLog.logger("延迟："+maction.getDelaytime());
                Thread.sleep(Long.parseLong(maction.getDelaytime()+""));
                break;
            case Action.CLICK:
                JfLog.logger("点击文字："+maction.getClicktext());
                AccessUtils.ClickViewrootBytext(getRootInActiveWindow(),mMyAccessibilityService,maction.getClicktext());
                break;

            case Action.SLIDE:
                JfLog.logger("滑动："+maction.getSlidestartend());
                //AccessUtils.ClickViewrootBytext(getRootInActiveWindow(),mMyAccessibilityService,maction.getClicktext());
                String slidestartend = maction.getSlidestartend();
                String[] split = slidestartend.split(",");
                Swipte(Integer.parseInt(split[0]),Integer.parseInt(split[1]),Integer.parseInt(split[2]),Integer.parseInt(split[3]),1000);
                break;


        }

    }


    public void cherkViewroot(AccessibilityNodeInfo info){
        if (info.getChildCount() == 0) {

            if(info.getText() != null){
                Log.i(TAG, info.getText().toString());
                if("签到领京豆".equals(info.getText().toString())){
                    //这里有一个问题需要注意，就是需要找到一个可以点击的View
                    Log.i(TAG, "Click"+",isClick:"+info.isClickable());
                    Rect nodeRect = new Rect();

                    info.getBoundsInScreen(nodeRect);
                    Log.i(TAG, "签到京豆的坐标"+""+nodeRect.centerX()+" Y:"+nodeRect.centerY());
                    info.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                    AccessibilityNodeInfo parent = info.getParent();
                    while(parent != null){
                        Log.i(TAG, "parent isClick:"+parent.isClickable());
                        if(parent.isClickable()){
                            parent.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                            break;
                        }
                        parent = parent.getParent();
                    }

                }
            }

        } else {
            for (int i = 0; i < info.getChildCount(); i++) {
                if(info.getChild(i)!=null){
                    cherkViewroot(info.getChild(i));
                }
            }
        }

    }
    int time=1;
    @Override
    public void onInterrupt() {

    }

    public void Swipte(int x1,int y1,int x2,int y2,int time){
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            Log.e(TAG,"Swipte");

            GestureDescription.Builder gestureBuilder = new GestureDescription.Builder();
            Path path = new Path();
            path.moveTo(x1,y1);
            path.lineTo(x2,y2);
//            if (event.getText() != null && event.getText().toString().contains("1")) {
//                //Swipe left
//                path.moveTo(rightSizeOfScreen, middleYValue);
//                path.lineTo(leftSideOfScreen, middleYValue);
//            } else {
//                //Swipe right
//                path.moveTo(leftSideOfScreen, middleYValue);
//                path.lineTo(rightSizeOfScreen, middleYValue);
//            }

            gestureBuilder.addStroke(new GestureDescription.StrokeDescription(path, 0, time));
            dispatchGesture(gestureBuilder.build(), new GestureResultCallback() {
                @Override
                public void onCompleted(GestureDescription gestureDescription) {

                    super.onCompleted(gestureDescription);
                }
            }, null);
        }

    }

    private KeyguardManager.KeyguardLock kl;
    /**
     * 系统是否在锁屏状态
     *
     * @return
     */
    private boolean isScreenLocked() {
        KeyguardManager keyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
        return keyguardManager.inKeyguardRestrictedInputMode();
    }

    private void wakeAndUnlock() {
        //获取电源管理器对象
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);

        //获取PowerManager.WakeLock对象，后面的参数|表示同时传入两个值，最后的是调试用的Tag
        @SuppressLint("InvalidWakeLockTag")
        PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "bright");

        //点亮屏幕
        wl.acquire(1000);

        //得到键盘锁管理器对象
        KeyguardManager km = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
        kl = km.newKeyguardLock("unLock");

        //解锁
        kl.disableKeyguard();



    }
    public void openScreen(Context context){
        //屏幕唤醒
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        @SuppressLint("InvalidWakeLockTag")
        PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP
                | PowerManager.SCREEN_DIM_WAKE_LOCK, "StartupReceiver");//最后的参数是LogCat里用的Tag
        wl.acquire();
    }

    public void setScreenLock(Context context){
        //屏幕解锁
        KeyguardManager km= (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
        KeyguardManager.KeyguardLock kl = km.newKeyguardLock("StartupReceiver");//参数是LogCat里用的Tag
        kl.disableKeyguard();
    }

    public void goApp(String packagename) {
        JfLog.logger( "goApp++++++++++++++++++++++++++++++++++++++++++++++++++++++：" + packagename);

        //com.jf.assistant
        Intent intent = getPackageManager().getLaunchIntentForPackage(packagename);


        if (intent != null) {

            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            getApplicationContext().startActivity(intent);

            JfLog.logger( "goApp++++++++++++++++++++++++++++++++++++++++++++++++++++++： 存在appintent FLAG_ACTIVITY_CLEAR_TOP" );
        }else {
            JfLog.logger( "goApp++++++++++++++++++++++++++++++++++++++++++++++++++++++： 不存在intent" );
        }


    }



    public static boolean isOpenAccessibility(Context context) {
        try {
            String service = context.getPackageName() + "/" + MyAccessibilityService.class.getCanonicalName();
            int accessibility = Settings.Secure.getInt(context.getApplicationContext().getContentResolver(),
                    Settings.Secure.ACCESSIBILITY_ENABLED);
            TextUtils.SimpleStringSplitter stringSplitter = new TextUtils.SimpleStringSplitter(':');
            //Log.e(TAG, "accessibility: " + accessibility);
            if (accessibility == 1) {
                String value = Settings.Secure.getString(context.getApplicationContext().getContentResolver(),
                        Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
                if (!TextUtils.isEmpty(value)) {
                    stringSplitter.setString(value);
                    while (stringSplitter.hasNext()) {
                        String next = stringSplitter.next();
                        if (next.equalsIgnoreCase(service)) {
                            return true;
                        }
                    }
                }
            }
        } catch (Settings.SettingNotFoundException e) {
            e.printStackTrace();
        }
        return false;
    }

}
